package util;

import android.os.Handler;
import android.os.Looper;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by mary on 2017/7/15.
 */

public class HttpUtil {
    private static final int CALLBACK_SUCCESSFUL = 0x01;
    private static final int CALLBACK_FAILED = 0x02;
    private static final String url="http://poem_helper.ngrok.cc/LoginTest";
    private static HttpUtil mInstance;
    private OkHttpClient okHttpClient;
    private Request.Builder builder;
    private Request request;
    private Handler handler;
    public static final MediaType FORM_CONTENT_TYPE
            = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
    private HttpUtil() {
        okHttpClient = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).readTimeout(10,TimeUnit.SECONDS).build();

        handler = new Handler(Looper.getMainLooper());
    }

    public static HttpUtil getInstance() {
        if (mInstance == null) {
            synchronized (HttpUtil.class) {
                if (mInstance == null) {
                    mInstance = new HttpUtil();
                }
            }
        }
        return mInstance;
    }

    //*************对外公布的方法************
    public static void login(String url, final ResultCallback resultCallback) {
        getInstance()._login(url, resultCallback);
        System.out.print(url);
    }
    public static void register(String url,final ResultCallback resultCallback){
        getInstance()._register(url,resultCallback);
    }


    //*************内部方法************
    private void _login(String url, final ResultCallback resultCallback) {

        final Request request = new Request.Builder().url(url).build();
        System.out.print(url);
        deliverResult(request, resultCallback);
    }
    private void _register(String url,final ResultCallback resultCallback){
        RequestBody body = RequestBody.create(FORM_CONTENT_TYPE, url);
        final Request request=new Request.Builder().url(url).post(body).build();
        deliverResult(request,resultCallback);
    }



    private void deliverResult(Request request, final ResultCallback callback) {
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                failedCallback(call, e, callback);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String string = response.body().string();
                    if(response.isSuccessful()) {
                        System.out.println("响应成功");
                        successCallback(string, callback);
                    }else{
                        System.out.print("响应失败");
                        string = "fail";
                    }
                } catch (IOException e) {
                    failedCallback(call, e, callback);
                }

            }
        });
    }

    private void successCallback(final String string, final ResultCallback callback) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onResponse(string);
                }
            }
        });
    }

    private void failedCallback(final Call call, final Exception e, final ResultCallback callback) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null)
                    callback.onError(call, e);
            }
        });
    }


    public static abstract class ResultCallback {
        public abstract void onError(Call call, Exception e);

        public abstract void onResponse(String response);
    }
}
